package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"micro_service/proto"
)

func main() {
	log.SetFlags(log.LstdFlags | log.Lmicroseconds)
	log.Println("Starting YOLO gRPC client...")

	// 连接服务器
	port := 50051
	log.Printf("Attempting to connect to server at localhost:%d", port)
	conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", port),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithBlock()) // 阻塞直到连接建立
	if err != nil {
		log.Fatalf("Failed to connect: %v", err)
	}
	log.Println("Successfully connected to server")
	defer conn.Close()

	// 创建客户端
	client := proto.NewYoloServiceClient(conn)
	log.Println("Created YOLO service client")

	// 设置上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 发送检测请求
	log.Println("Sending detection request to server...")
	response, err := client.Detect(ctx, &proto.DetectRequest{
		ImagePath:       ".\\bus.jpg",
		ModelPath:       "d:\\work\\svn\\4GCEnhanced\\test\\yolo\\yolo11n.onnx",
		ClassLabels:     []string{}, // 使用默认标签
		OnnxruntimePath: "d:\\work\\svn\\4GCEnhanced\\test\\yolo\\onnxruntime.dll",
	})

	if err != nil {
		log.Fatalf("Detection failed: %v", err.Error())
	}

	// 处理响应
	if !response.Success {
		log.Fatalf("Detection failed: %s", response.Message)
	}

	log.Printf("Detection successful! Found %d objects.", len(response.Boxes))
	for i, box := range response.Boxes {
		log.Printf("Object %d: %s (confidence: %.2f) at [x1: %.2f, y1: %.2f, x2: %.2f, y2: %.2f]",
			i+1, box.Label, box.Confidence, box.X1, box.Y1, box.X2, box.Y2)
	}
}
